<?php

namespace app\common\model;

use think\Model;

class UserSignin extends Model
{
    // 开启自动写入时间戳字段
//    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';

    //今日是否签到
    public function isSigned($userId)
    {
        $today = strtotime('today');
        $where = [
            'user_id' => $userId,
            'signtime' => $today
        ];

        $id = self::where($where)->value('id');
        if (!$id) {
            return false;
        }

        return true;
    }

    // 今日签到
    public function signed($userId)
    {
        $today = strtotime('today');

        $data = [
            'user_id' => $userId,
            'signtime' => $today,
            'createtime' => time(),
        ];
        $ret = self::create($data);

        if (!$ret->id) {
            return false;
        }

        return true;
    }

    // 获取连续签到天数
    public function getSignedDays($userId)
    {
        $days = 0;
        $today = strtotime('today');
        $where = [
            'user_id' => $userId,
            'signtime' => $today
        ];
        $id = self::where($where)->value('id');
        if ($id) {
            $days = 1;
        }

        $flag = true;
        $i = 1;
        do {
            $signTime = $today - $i * 86400;
            $map = [
                'user_id' => $userId,
                'signtime' => $signTime
            ];

            $id = self::where($map)->value('id');
            if (!$id) {
                $flag = false;
            } else {
                $i++;
                $days++;
            }

        } while ($flag);

        return $days;
    }

    //本周的签到情况
    public function getSignedDaysByWeek($userId)
    {
        //本周一
        $start = strtotime(date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600))); //w为星期几的数字形式,这里0为周日
        //本周日
        $end = strtotime(date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600))); //同样使用w,以现在与周日相关天数算
        $days = (int)ceil(($end - $start) / 86400) + 1;
        $data = [];
        for ($i = 0; $i < $days; $i++) {
            $signTime = $start + $i * 86400;
            $map = [
                'user_id' => $userId,
                'signtime' => $signTime
            ];

            $id = self::where($map)->value('id');

            if (!$id) {
                $isSigned = false;
            } else {
                $isSigned = true;
            }

            $item = [
                'day' => (int)($i + 1),
                'isSigned' => $isSigned,
            ];

            $data[] = $item;
        }

        return $data;
    }
}
